package com.haitaoit.chengquan.versions;

import android.app.Activity;
import android.app.AlertDialog.Builder;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnClickListener;
import android.content.Intent;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.Uri;
import android.os.Environment;
import android.os.Handler;
import android.os.Message;
import android.telephony.TelephonyManager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.ProgressBar;

import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.haitaoit.chengquan.R;
import com.haitaoit.chengquan.base.BackCall;
import com.haitaoit.chengquan.base.ExitApplication;
import com.haitaoit.chengquan.base.MyCallBack;
import com.haitaoit.chengquan.main.MainActivity;
import com.haitaoit.chengquan.main.MianButtonActivity;
import com.haitaoit.chengquan.module.login.LoginActivity;
import com.haitaoit.chengquan.ui.equipment.request.ApiRequest;
import com.haitaoit.chengquan.ui.equipment.response.LoginBean;
import com.haitaoit.chengquan.utils.Constant;
import com.haitaoit.chengquan.utils.DialogUtil;
import com.haitaoit.chengquan.utils.GetSign;
import com.haitaoit.chengquan.utils.HttpUtilsSingle;
import com.haitaoit.chengquan.utils.NameValuePairSign;
import com.haitaoit.chengquan.utils.PreferenceUtils;
import com.haitaoit.chengquan.utils.ToastUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import static android.content.Context.TELEPHONY_SERVICE;

public class UpdateManagerUtils {
    /* 下载中 */
    private static final int DOWNLOAD        = 1;
    /* 下载结束 */
    private static final int DOWNLOAD_FINISH = 2;
    // /* 保存解析的XML信息 */
    // HashMap<String, String> mHashMap;
    /* 下载保存路径 */
    private String mSavePath;
    /* 记录进度条数量 */
    private int    progress;
    /* 是否取消更新 */
    private boolean cancelUpdate = false;

    private Context     mContext;
    /* 更新进度条 */
    private ProgressBar mProgress;
    private Dialog      mDownloadDialog;

    ToastUtils toast;
    private VersionModel versions;

    private Handler mHandler = new Handler() {
        public void handleMessage(Message msg) {
            switch (msg.what) {// 正在下载
                case DOWNLOAD:// 设置进度条位置
                    mProgress.setProgress(progress);
                    break;
                case DOWNLOAD_FINISH:// 安装文件
                    installApk();
                    break;
                case 3:
                    ((MainActivity) mContext).finish();
                    break;
                case 4:
                    Intent intent = new Intent(mContext, MianButtonActivity.class);
                    intent.putExtra("index", 0);
                    mContext.startActivity(intent);
                    ((MainActivity) mContext).finish();
                    break;
                default:
                    break;
            }
        }
    };
    private Dialog mDlg;

    public UpdateManagerUtils(Context context) {
        this.mContext = context;

        // this.versions=new VersionModel();
    }

    /**
     * 检测软件更新
     *
     * @return
     */
    public UpdateManagerUtils checkUpdate() {
        versions = new VersionModel();
        httpVersionCode();
        return this;
    }

    BackCall backCall;

    public void setBackCall(BackCall backCall) {
        this.backCall = backCall;
    }

    /**
     * 检查软件是否有更新版本
     *
     * @return
     */
    private boolean isUpdate() {
        String tag = "N";
        // 获取当前软件版本
        int versionCode = getVersionCode(mContext);
        //获取本地版本号
        String versionName = getVersionName(mContext);
        //这是网络上获取的版本号码
        String serviceName = versions.getAndroid_vs_name();

        int vs_name1 = 0;
        int vs_name2 = 0;
        int vs_name3 = 0;
        int sv_name1 = 0;
        int sv_name2 = 0;
        int sv_name3 = 0;
        try {
            if (versionName.contains(".")) {//等于-1表示这个字符串中没有.这个字符
                String[] vs_name = versionName.split("\\.");
                for (int i = 0; i < vs_name.length; i++) {
                    if (!vs_name[i].equals("")) {
                        if (i == 0) {
                            vs_name1 = Integer.valueOf(vs_name[0]);
                        }
                        if (i == 1) {
                            vs_name2 = Integer.valueOf(vs_name[1]);
                        }
                        if (i == 2) {
                            vs_name3 = Integer.valueOf(vs_name[2]);
                        }
                    }
                }
            }
            if (serviceName.contains(".")) {
                String[] sv_name = serviceName.split("\\.");
                for (int i = 0; i < sv_name.length; i++) {
                    if (!sv_name[i].equals("")) {
                        if (i == 0) {
                            sv_name1 = Integer.valueOf(sv_name[0]);
                        }
                        if (i == 1) {
                            sv_name2 = Integer.valueOf(sv_name[1]);
                        }
                        if (i == 2) {
                            sv_name3 = Integer.valueOf(sv_name[2]);
                        }
                    }
                }
            }
            //            if (null != versions) {
            //                int serviceCode = Integer.valueOf(versions.getAndroid_version());
            //                // 版本判断
            ////                if (serviceCode > versionCode) {//通过versionCode判断
            ////                    tag = "Y";
            ////                } else
            //
            //
            //                if (serviceCode == versionCode) {//通过versionName来判断
            //                    if (sv_name1 > vs_name1) {
            //                        tag = "Y";
            //                    } else if (sv_name1 == vs_name1) {
            //                        if (sv_name2 > vs_name2) {
            //                            tag = "Y";
            //                        } else if (sv_name2 == vs_name2) {
            //                            if (sv_name3 > vs_name3) {
            //                                tag = "Y";
            //                            }
            //                        }
            //                    }
            //                }
            //            }
        } catch (Exception e) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Message message = mHandler.obtainMessage();
                            message.what = 4;
                            mHandler.sendMessage(message);

                        }
                    }, 10);

                }
            }).start();

            ToastUtils.showToast("版本信息有误，请确认后台版本信息是否规范！");
            tag = "N";
        }
        //        if (tag.equals("Y")) {
        //            return true;
        //        } else {
        //            return false;
        //        }

        if (sv_name1 > vs_name1) {

            return true;
        } else if (sv_name1 == vs_name1) {


            if (sv_name2 > vs_name2) {
                return true;
            } else if (sv_name2 == vs_name2) {


                if (sv_name3 > vs_name3) {
                    return true;
                } else if (sv_name3 == vs_name3) {

                    return false;
                } else {
                    return false;
                }

            } else {
                return false;
            }

        } else {
            return false;
        }
    }


    private void httpVersionCode() {
        int i = (int) Math.floor(Math.random() * 9000 + 1000);
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("rnd", i + ""));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("rnd", i + "");
        params.addQueryStringParameter("sign", sign);

        HttpUtilsSingle.doGet(mContext, false, Constant.Update_Version, params, new RequestCallBack<String>() {
            @Override
            public void onFailure(HttpException arg0, String arg1) {
                ToastUtils.showToast("数据请求失败，请检查网络!");
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Message message = mHandler.obtainMessage();
                                message.what = 4;
                                mHandler.sendMessage(message);
                            }
                        }, 2000);
                    }
                }).start();

            }

            @Override
            public void onSuccess(ResponseInfo<String> arg0) {
                String jsondata = arg0.result.toString();
                try {
                    JSONObject obj = new JSONObject(jsondata);
                    String Errcode = obj.getString("ErrCode");
                    String Errmsg = obj.getString("ErrMsg");
                    switch (Integer.valueOf(Errcode)) {
                        case 1:
                            ToastUtils.showToast(Errmsg);
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    mHandler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            Message message = mHandler.obtainMessage();
                                            message.what = 4;
                                            mHandler.sendMessage(message);
                                        }
                                    }, 10);
                                }
                            }).start();
                            break;
                        case 0:
                            Gson gson = new Gson();
                            versions = gson.fromJson(obj.getJSONObject("Response")
                                    .toString(), new TypeToken<VersionModel>() {
                            }.getType());
                            /**
                             * 检测软件更新
                             */
                            if (isUpdate()) {
                                // 显示提示对话框
                                showNoticeDialog();
                            } else {
                                //                                ToastUtils.showToast("已经是最新版本");

                                Runnable runnable = new Runnable() {
                                    public void run() {
                                        autoLogin();
                                    }
                                };
                                mHandler.postDelayed(runnable, 2000);
                            }
                            break;
                        default:
                            new Thread(new Runnable() {
                                @Override
                                public void run() {
                                    mHandler.postDelayed(new Runnable() {
                                        @Override
                                        public void run() {
                                            Message message = mHandler.obtainMessage();
                                            message.what = 4;
                                            mHandler.sendMessage(message);
                                        }
                                    }, 10);
                                }
                            }).start();
                            break;
                    }
                } catch (JSONException e) {

                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Message message = mHandler.obtainMessage();
                                    message.what = 4;
                                    mHandler.sendMessage(message);
                                }
                            }, 10);
                        }
                    }).start();
                }
            }
        });
    }

    private void autoLogin() {
        final String name = PreferenceUtils.getPrefString("username", "");
        final String pwd = PreferenceUtils.getPrefString("password", "");
        //获取手机唯一标识
        TelephonyManager TelephonyMgr = (TelephonyManager) mContext.getSystemService(TELEPHONY_SERVICE);
        String equipment = TelephonyMgr.getDeviceId();
        List<NameValuePairSign> list = new ArrayList<NameValuePairSign>();
        list.add(new NameValuePairSign("phone", name));
        list.add(new NameValuePairSign("password", pwd));
        list.add(new NameValuePairSign("equipment", equipment));
        list.add(new NameValuePairSign("registration_id", ExitApplication.getInstance().getJPushId()));
        String sign = GetSign.genPackageSign(list);

        RequestParams params = new RequestParams();
        params.addQueryStringParameter("phone", name);
        params.addQueryStringParameter("password", pwd);
        params.addQueryStringParameter("equipment", equipment);
        params.addQueryStringParameter("registration_id", ExitApplication.getInstance().getJPushId());
        params.addQueryStringParameter("sign", sign);
        //api/User/GetUserlogin?equipment={equipment}&phone={phone}&password={password}&sign={sign}
        Map<String, String> map = new HashMap<String, String>();
        map.put("phone", name);
        map.put("password", pwd);
        map.put("equipment", equipment);
        map.put("registration_id", ExitApplication.getInstance().getJPushId());
        map.put("sign", sign);
        ApiRequest.userLogin(map, new MyCallBack<LoginBean>(mContext, true) {
            @Override
            public void onSuccessful(LoginBean response) {
                if (response.getErrCode() == 0) {
                    PreferenceUtils.setPrefString("username", name);
                    PreferenceUtils.setPrefString("password", pwd);
                    PreferenceUtils.setPrefString("user_id", response.getResponse().getUser_id());
                    // 账号的类别
                    PreferenceUtils.setPrefString("account_type", response.getResponse().getType());
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Message message = mHandler.obtainMessage();
                                    message.what = 4;
                                    mHandler.sendMessage(message);
                                }
                            }, 10);
                        }
                    }).start();
                } else {
                    new Thread(new Runnable() {
                        @Override
                        public void run() {
                            mHandler.postDelayed(new Runnable() {
                                @Override
                                public void run() {
                                    Message message = mHandler.obtainMessage();
                                    message.what = 4;
                                    mHandler.sendMessage(message);
                                }
                            }, 10);
                        }
                    }).start();
                }
            }

            @Override
            protected void onError(Throwable throwable) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Message message = mHandler.obtainMessage();
                                message.what = 4;
                                mHandler.sendMessage(message);
                            }
                        }, 10);
                    }
                }).start();
            }
        });
    }

    /**
     * 获取软件版本号
     *
     * @param context
     * @return
     */
    private int getVersionCode(Context context) {
        int versionCode = 0;
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionCode = context.getPackageManager().getPackageInfo(
                    "com.haitaoit.chengquan", 0).versionCode;
        } catch (NameNotFoundException e) {
            e.printStackTrace();
        }
        return versionCode;
    }

    /**
     * 获取软件版本名
     * 1.1.0
     *
     * @param context
     * @return
     */
    private String getVersionName(Context context) {
        String versionName = "";
        try {
            // 获取软件版本号，对应AndroidManifest.xml下android:versionCode
            versionName = context.getPackageManager().getPackageInfo(
                    context.getPackageName(), 0).versionName;
        } catch (NameNotFoundException e) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    mHandler.postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            Message message = mHandler.obtainMessage();
                            message.what = 4;
                            mHandler.sendMessage(message);
                        }
                    }, 10);
                }
            }).start();
        }
        return versionName;
    }

    /**
     * 显示软件更新对话框
     */
    private void showNoticeDialog() {
        // 确定
        // 显示下载对话框
        // 取消
/*Intent intent = new Intent(mContext, MainFragmentActivity.class);MainTabActivity
intent.putExtra("index", 0);
mContext.startActivity(intent);*/ /**
         * 不应该把当前界面给finsh掉
         */ //                                ((Activity) mContext).finish();
        mDlg = DialogUtil.showInfoDialog1(mContext, "软件更新",
                "检测到新版本，立即更新吗？", "稍后更新", "更新", new BackCall() {
                    public void deal(int which, Object... obj) {
                        switch (which) {
                            case R.id.cancel:// 确定
                                // 显示下载对话框
                                showDownloadDialog();
                                break;
                            case R.id.confirm:// 取消
                                ToastUtils.showToast("请升级之后使用");

                                Intent intent = new Intent(mContext, MianButtonActivity.class);
                                mContext.startActivity(intent);
                                mDlg.dismiss();


                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        mHandler.postDelayed(new Runnable() {
                                            @Override
                                            public void run() {
                                                Message message = mHandler.obtainMessage();
                                                message.what = 3;
                                                mHandler.sendMessage(message);

                                            }
                                        }, 10);

                                    }
                                }).start();

                                break;
                        }
                        super.deal(which);
                    }
                });
        mDlg.show();

    }

    /**
     * 显示软件下载对话框
     */
    private void showDownloadDialog() {
        // 构造软件下载对话框
        Builder builder = new Builder(mContext);
        builder.setTitle(R.string.soft_updating);
        // 给下载对话框增加进度条
        final LayoutInflater inflater = LayoutInflater.from(mContext);
        View v = inflater.inflate(R.layout.softupdate_progress, null);
        mProgress = (ProgressBar) v.findViewById(R.id.update_progress);
        builder.setView(v);
        // 取消更新
        builder.setNegativeButton(R.string.soft_update_cancel, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
                // 设置取消状态
                cancelUpdate = true;
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Message message = mHandler.obtainMessage();
                                message.what = 4;
                                mHandler.sendMessage(message);
                            }
                        }, 10);
                    }
                }).start();
            }
        });
        mDownloadDialog = builder.create();
        mDownloadDialog.setCanceledOnTouchOutside(true);
        mDownloadDialog.setCancelable(false);
        mDownloadDialog.show();

        //        builder.create().setOnDismissListener(new DialogInterface.OnDismissListener() {
        //            @Override
        //            public void onDismiss(DialogInterface dialog) {
        //                String account_type = PreferenceUtils.getPrefString("account_type", "");
        //                if(TextUtils.equals(account_type,"1")||TextUtils.isEmpty(account_type)) {
        //                    Intent intent = new Intent(mContext, MainTabActivity.class);
        //                    intent.putExtra("index", 0);
        //                    mContext.startActivity(intent);
        //                }else {
        //                    Intent intent = new Intent(mContext, MainTabActivityTwo.class);
        //                    intent.putExtra("index", 0);
        //                    mContext.startActivity(intent);
        //                }
        //            }
        //        });
        // 现在文件
        downloadApk();
    }

    /**
     * 下载apk文件
     */
    private void downloadApk() {
        // 启动新线程下载软件
        new downloadApkThread().start();
    }

    /**
     * 下载文件线程
     *
     * @author coolszy
     * @date 2012-4-26
     * @blog http://blog.92coding.com
     */
    private class downloadApkThread extends Thread {
        @Override
        public void run() {
            try {
                // 判断SD卡是否存在，并且是否具有读写权限
                if (Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
                    // 获得存储卡的路径
                    String sdpath = Environment.getExternalStorageDirectory() + "/";
                    mSavePath = sdpath + "download";
                    URL url = new URL(versions.getAndroid_vs_url());
                    // 创建连接
                    HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                    conn.connect();
                    // 获取文件大小
                    int length = conn.getContentLength();
                    // 创建输入流
                    InputStream is = conn.getInputStream();

                    File file = new File(mSavePath);
                    // 判断文件目录是否存在
                    if (!file.exists()) {
                        file.mkdir();
                    }
                    File apkFile = new File(mSavePath, versions.getAndroid_vs_name());
                    FileOutputStream fos = new FileOutputStream(apkFile);
                    int count = 0;
                    // 缓存
                    byte buf[] = new byte[1024];
                    // 写入到文件中
                    do {
                        int numread = is.read(buf);
                        count += numread;
                        // 计算进度条位置
                        progress = (int) (((float) count / length) * 100);
                        // 更新进度
                        mHandler.sendEmptyMessage(DOWNLOAD);
                        if (numread <= 0) {
                            // 下载完成
                            mHandler.sendEmptyMessage(DOWNLOAD_FINISH);
                            break;
                        }
                        // 写入文件
                        fos.write(buf, 0, numread);
                    } while (!cancelUpdate);// 点击取消就停止下载.
                    fos.close();
                    is.close();


                }
            } catch (Exception e) {
                new Thread(new Runnable() {
                    @Override
                    public void run() {
                        mHandler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Message message = mHandler.obtainMessage();
                                message.what = 4;
                                mHandler.sendMessage(message);
                            }
                        }, 10);
                    }
                }).start();
            }
            // 取消下载对话框显示
            mDownloadDialog.dismiss();
        }
    }

    /**
     * 安装APK文件
     */
    private void installApk() {
        File apkfile = new File(mSavePath, versions.getAndroid_vs_name());
        if (!apkfile.exists()) {
            return;
        }
        // 通过Intent安装APK文件
        Intent i = new Intent(Intent.ACTION_VIEW);
        i.setDataAndType(Uri.parse("file://" + apkfile.toString()),
                "application/vnd.android.package-archive");
        mContext.startActivity(i);
    }

    public void onDestroyDoing() {
        mHandler.removeCallbacksAndMessages(null);
        if (mDlg != null) {
            mDlg = null;
        }
    }
}
